<template>
    <div style="display: flex">
        <div
             v-loading="loading"
             element-loading-text="拼命加载中"
             element-loading-spinner="el-icon-loading"
             element-loading-background="rgba(0, 0, 0, 0.8)"
             style="width: 100%"
            >
            <div>
                <el-autocomplete
                        v-model="keywords"
                        style="width: 30%"
                        :fetch-suggestions="querySearchAsync"
                        placeholder="请输入内容"
                        @select="handleSelect"
                ></el-autocomplete>
                <el-button style="margin-left: 5px" type="danger" icon="el-icon-delete" circle @click="reset"></el-button>
                <span style="margin-left: 10px;font-size: 10px;">
                      <span>经度：{{ form.lng }}</span>
                      <span style="margin-left: 10px;">纬度：{{ form.lat }}</span>
                      <span >地址：{{form.address}}</span>
                </span>
            </div>
            <div id="container" class="container"></div>
        </div>
    </div>
</template>

<script>
    import AMapLoader from "@amap/amap-jsapi-loader";
    window._AMapSecurityConfig = {
        // 安全密钥
        securityJsCode: "d4e4320686ef905014772a2a5f019e9b",
    };
    export default {
        name: "GodMap",
        props:{
            godAdr:Object
        },
        data() {
            return {
                // 地图实例
                map: null,
                // 标记点
                marker: "",
                //当前定位
                geolocation:"",
                // 地址逆解析
                geoCoder: null,
                // 搜索提示
                AutoComplete: null,
                //缩放控件
                ToolBar:null,
                //地图放大镜
                HawkEye:null,
                // 搜索关键字
                keywords: "",
                // 位置信息
                form: {
                    lng: "",
                    lat: "",
                    address:'',
                },
                // 搜索节流阀
                loading: false,
                // 搜索提示信息
                options: [],
            };
        },
        created() {
            this.form = this.godAdr;
            this.initMap();

        },
        methods: {
            reset(){
                this.keywords = '';
                this.form = this.godAdr;
                this.toGeoCoder();
            },
            initMap() {
                AMapLoader.load({
                    // 你申请的Key
                    key: "52cd1aaa69a24ba68513fe4be10e3806",
                    version: "2.0",
                    // 需要用到的插件
                    plugins: ["AMap.Geocoder", "AMap.AutoComplete","AMap.ToolBar","AMap.HawkEye"],
                })
                    .then((AMap) => {
                        this.map = new AMap.Map("container", {
                            viewMode: "2D", //是否为3D地图模式
                            zoom: 23, //初始化地图级别
                            center: [this.form.lng, this.form.lat], //初始化地图中心点位置
                        });
                        //地址逆解析插件
                        this.geoCoder = new AMap.Geocoder({
                            radius: 3000, //范围，默认：500
                        });
                        // 搜索提示插件
                        this.AutoComplete = new AMap.AutoComplete({ city: "全国" });
                        this.ToolBar =  new AMap.ToolBar({
                            position: {
                                bottom: '210px',
                                right: '35px'
                            }
                        });
                        this.HawkEye =  new AMap.HawkEye({
                            position: {
                                bottom: '110px',
                                left: '35px'
                            }
                        });
                        //定位功能不好用，访问时间过久
                        /*this.geolocation = new AMap.Geolocation({
                            enableHighAccuracy: true, // 是否使用高精度定位，默认:true
                            timeout: 10000, // 超过10秒后停止定位，默认：5s
                            showButton: true, // 显示定位按钮，默认：true
                            position: 'RB', // 定位按钮的停靠位置
                            offset: [10, 20], // 定位按钮与设置的停靠位置的偏移量，默认：[10, 20]
                            showMarker: true, // 定位成功后在定位到的位置显示点标记，默认：true
                            panToLocation: true, // 定位成功后将定位到的位置作为地图中心点，默认：true
                            zoomToAccuracy: true // 定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
                        })
                        this.map.addControl(this.geolocation);
                        this.geolocation.getCurrentPosition() // 自动获取定位
                        // 返回定位信息
                        this.geolocation.on('complete', (res) => {
                            console.log('res', res)
                        })
                        // 返回定位出错信息
                        this.geolocation.on('error', (err) => {
                            console.log('err', err)
                        })
                        */
                        this.map.addControl(this.ToolBar);
                        this.map.addControl(this.HawkEye);
                        // 逆解析地址
                        this.toGeoCoder();
                        //点击获取经纬度;
                        this.map.on("click", (e) => {
                            // 获取经纬度
                            this.form.lng = e.lnglat.lng;
                            this.form.lat = e.lnglat.lat;
                            this.toGeoCoder();
                        });
                    })
                    .catch((err) => {
                        // 错误
                    });
            },
            // 标记点
            setMapMarker() {

                this.marker = new AMap.Marker({
                    map: this.map,
                    position: [this.form.lng, this.form.lat],
                });

                this.map.add(this.marker);
                // 自动适应显示想显示的范围区域
                this.map.setFitView();
            },
            // 清除点
            removeMarker() {
                if (this.marker) {
                    this.map.remove(this.marker);
                }
            },
            // 逆解析地址
            toGeoCoder() {
                this.loading= true;
                let lnglat = [this.form.lng, this.form.lat];
                this.geoCoder.getAddress(lnglat, (status, result) => {
                    console.log("逆解析地址结果：");
                    console.log(result);
                    if (status === "complete") {
                        this.form.address = result.regeocode.formattedAddress;
                        // 清除点
                        this.removeMarker();
                        // 标记点
                        this.setMapMarker();
                    }else {
                        this.form.address = '';
                    }
                    this.loading= false;
                });
            },
            fromGeoCoder(addr){
                console.log("顺解析地址");
                console.log(addr);
                this.geoCoder.getLocation(addr, (status, result) =>{
                    console.log("顺解析地址结果：");
                    console.log(result);
                    if (status === "complete") {
                        this.form = {
                            lng: result.geocodes[0].location.lng,
                            lat: result.geocodes[0].location.lat,
                        };
                        this.toGeoCoder();
                    }
                });
            },
            querySearchAsync(queryString, cb){
                if (queryString) {
                    this.AutoComplete.search(queryString, (status, result) => {
                        if(status === 'complete'){
                            this.options = result.tips;
                            for (let i = 0; i < this.options.length; i++) {
                                this.options[i].value = this.options[i].name;
                            }
                        }else {
                            this.options = [];
                        }
                        cb(this.options);
                    });
                } else {
                    this.options = [];
                    cb(this.options);
                }
            },
            handleSelect(val){
                // 清空时不执行后面代码
                if (!val) {
                    return;
                }
                if(val.location == null ||val.location ==""||val.location =="undefined"){
                    console.log("无坐标，查询名称：");
                    console.log(val)
                    this.fromGeoCoder(val.value);

                }else{
                    this.form = {
                        lng: val.location.lng,
                        lat: val.location.lat,
                    };
                    this.toGeoCoder();
                }


            },

        }
    };
</script>

<style>
    .container {
        margin-top: 10px;
        width: 100%;
        height: 300px;
    }
</style>